package org.phalanx.servlet.websession;

import java.util.ArrayList;
import java.util.Iterator;

import org.phalanx.server.PhalanxServer;
import org.phalanx.server.ServerCache.AbstractCacheHandler;
import org.phalanx.server.ServerCache.Cache;
import org.phalanx.server.ServerCache.CacheManager;
import org.phalanx.server.ServerCache.Cacheable;
import org.phalanx.server.game.PhalanxGameSettings;

public class JoinFeedCacheHandler implements AbstractCacheHandler {

	@Override
	public boolean addElementToDB(Cache c, Object newKey, Cacheable newElement) {
		c.put(newKey, newElement);
		return true;
	}

	@Override
	public boolean deleteObjectFromDB(Cache c, Object newKey,
			Cacheable newElement) {
		// TODO Auto-generated method stub
		c.delete(newKey);
		return true;
	}

	@Override
	public ArrayList<Cacheable> getMultipleObjectsFromDB(Cache c,
			Object newKey, boolean cacheUpdate) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Cacheable getObjectFromDB(Cache c, Object newKey, boolean cacheUpdate) {
		// TODO Auto-generated method stub
		return c.get(newKey);
	}

	@Override
	public boolean populateCache(Cache c) {
		CacheManager cacheMgr = PhalanxServer.getServerInstance().getCacheManager();
		
		Iterator<Object> i = cacheMgr.getCache("GameListCache").getInternalCacheTable().keySet().iterator();
		
		while (i.hasNext()){
			Integer gameId = (Integer)i.next();
			
			Cacheable pState = cacheMgr.getElementNoCacheUpdate("PlayerStateCache", gameId);
			
			if (pState == null){
				// If there is no player state, the game must only be halfway
				// created and therefore requires a joinfeed
				
				PhalanxGameSettings settings = (PhalanxGameSettings)cacheMgr.getElement("GameListCache", gameId);
				
				JoinFeed jFeed = new JoinFeed(gameId, settings.getGameCreatorId());
				c.put(gameId, jFeed);
			}
		}
		
		return true;
	}

	@Override
	public boolean updateElementToDB(Cache c, Object newKey,
			Cacheable newElement) {
		// TODO Auto-generated method stub
		addElementToDB(c, newKey, newElement);
		return true;
	}

}
